<template>
  <div>
    <audio ref="audio">
      <source :src="mp3Url">
    </audio>
    <n-space justify="space-between">
      <n-el>
        <n-button
            type="primary"
            style="margin-bottom: 10px;margin-left: 10px;"
            @click="initBatchOperationForm">
          自动任务
        </n-button>
        <n-button type="primary" style="margin-bottom: 10px;margin-left: 10px;" @click="upscaleModalShow = true">
          批量放大
        </n-button>
      </n-el>
      <n-el>
        <n-row>
          <n-select
              style="width: 200px;"
              :options="storyBoardSelectType"
              v-model:value="storyBoardSelectOption"
              @update:value="getStoryBoardByChapterId">
          </n-select>
        </n-row>
      </n-el>
    </n-space>
    <n-data-table
        :single-line="false"
        :bordered="true"
        :loading="tableLoading"
        :bottom-bordered="true"
        :columns="createColumns"
        :data="boardList"
        :style="{ height: `${clientHeight - 129}px` }"
        flex-height
    />
    <n-modal v-model:show="imageModelShow">
      <n-card
          style="width: 500px"
          :bordered="false"
          size="huge"
          role="dialog"
          aria-modal="true"
      >
        <img-model :row="selectRow"></img-model>
      </n-card>
    </n-modal>
    <n-drawer v-model:show="detailDesignShow" :width="drawerWidth" :close-on-esc="false"
              @after-leave="getStoryBoardByChapterId">
      <n-drawer-content title="画面高级调整" :closable="true">
        <detailDesign
            :story-board-list="boardList"
            :select-num="selectIndex"
            :reload-story-boards="getStoryBoardByChapterId"
        ></detailDesign>
      </n-drawer-content>
    </n-drawer>


    <n-modal
        v-model:show="batchOperationForm.batchOperationModalShow"
        :mask-closable=false
    >
      <n-card
          style="width: 600px"
          title="自动任务"
          :bordered="false"
          size="huge">
        <n-form>
          <n-form-item label="任务类型">
            <n-radio-group v-model:value="batchOperationForm.batchOperationType">
              <n-radio value='0'>生成图片和音频</n-radio>
              <n-radio value="1">仅生成图片</n-radio>
              <n-radio value="2">仅生成音频</n-radio>
            </n-radio-group>
          </n-form-item>
          <n-grid x-gap="10">
            <n-grid-item :span="12">
              <n-form-item label="开始序号">
                <n-input-number :precision="0"
                                v-model:value="batchOperationForm.batchOperationStartNum"></n-input-number>
              </n-form-item>
            </n-grid-item>
            <n-grid-item :span="12">
              <n-form-item label="结束序号">
                <n-input-number :precision="0" v-model:value="batchOperationForm.batchOperationEndNum"></n-input-number>
              </n-form-item>
            </n-grid-item>
            <n-grid-item :span="12">
              <n-form-item :show-label="false">
                <n-checkbox v-model:checked="skipFlag">跳过已完成</n-checkbox>
              </n-form-item>
            </n-grid-item>
            <n-grid-item :span="12">
              <n-form-item :show-label="false">
                <n-checkbox v-model:checked="runInBack">后台运行</n-checkbox>
              </n-form-item>
            </n-grid-item>
          </n-grid>
          <n-grid ref="progressGridRef" v-if="taskStatus.totalNum!=0">
            <n-grid-item :span="24">
              <n-space justify="space-around">
                <n-statistic label="当前进度" :value="currentTaskNum">
                  <template #prefix>
                  </template>
                  <template #suffix>
                    / {{ taskStatus.totalNum }}
                  </template>
                </n-statistic>
                <n-statistic label="成功/失败">
                  <template #prefix>
                    {{ taskStatus.successNum }}
                  </template>
                  <template #suffix>
                    /
                    <n-gradient-text type="error">{{ taskStatus.failNum }}</n-gradient-text>
                  </template>
                </n-statistic>
              </n-space>
            </n-grid-item>
            <n-grid-item :span="24">
              <n-progress
                  type="line"
                  :percentage=" Math.round((currentTaskNum/taskStatus.totalNum) * 100) "
                  :height="30"
                  :border-radius="5"
                  :fill-border-radius="0"
                  :indicator-placement="'inside'"
                  :processing="batchOperationForm.batchOperationFlag"
              />
            </n-grid-item>
          </n-grid>
        </n-form>

        <template #footer>
          <n-space justify="space-between">
            <n-button
                type="primary"
                @click="startTask"
                :loading="batchOperationForm.loading"
                v-if="!batchOperationForm.batchOperationFlag">开始任务
            </n-button>
            <n-button
                type="warning"
                v-if="!batchOperationForm.batchOperationFlag"
                @click="batchOperationForm.batchOperationModalShow = false">取消
            </n-button>
          </n-space>
          <n-button
              :block="true"
              type="error"
              style="margin-top:5px;"
              @click="shutDownTask"
              v-if="batchOperationForm.batchOperationFlag">终止任务
          </n-button>
        </template>
      </n-card>
    </n-modal>

    <n-modal
        v-model:show="progressModal"
        class="custom-card"
        style="width: 500px"
        preset="card"
        title="任务进度"
        size="huge"
        :bordered="false"
    >
      <n-space justify="space-around">
        <n-statistic label="当前进度" :value="currentTaskNum">
          <template #prefix>
          </template>
          <template #suffix>
            / {{ boardList.length }}
          </template>
        </n-statistic>
        <n-statistic label="成功/失败">
          <template #prefix>
            {{ taskStatus.successNum }}
          </template>
          <template #suffix>
            / {{ taskStatus.failNum }}
          </template>
        </n-statistic>
      </n-space>
      <n-progress
          type="line"
          :percentage=" Math.round(currentTaskNum/boardList.length*100) "
          :height="30"
          :border-radius="5"
          :fill-border-radius="0"
      />
    </n-modal>

    <n-modal
        v-model:show="upscaleModalShow"
        :mask-closable=false
        :closable="true"
    >
      <UpscalerView
          :paintConfig="paintConfig"
          :resourceId="resourceId"
          :upsacleList="boardList"
          :closeFunction="upscalerViewClose"
          :storyId="props.story.id">
      </UpscalerView>
    </n-modal>
    <n-drawer display-directive="show" v-model:show="openPoseViewShow" :width="drawerWidth">
      <n-drawer-content title="从骨骼图选择" closable>
        <OpenPoseView mode="choseOpenPose" :choseOpenPose="chosenOpenPose"></OpenPoseView>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>
<script setup lang="ts">
import {NButton, NGrid, NIcon, NImage, NInput, NRadio, NRadioGroup, NSpace, NTreeSelect, useMessage} from 'naive-ui'
import {defineComponent, h, onMounted, reactive, ref} from "vue";
import {storyController} from "@/api/story/story.api";
import imgModel from '@/views/pages/create/novel/components/imgModel.vue'
import detailDesign from '@/views/pages/create/novel/components/detailDesign.vue'

const message = useMessage()
const tableLoading = ref(false)
//@ts-ignore
import fileFunction from '@/libs/globalFunction/file.js'
import {storyBoardController} from "@/api/controller/story/storyBoard.api"
import {storeToRefs} from "pinia"
import {useSystemStore} from "@/store/modules/useSystemStore"
import {
  CaretForwardCircleSharp as CaretForwardCircleSharpIcon,
} from '@vicons/ionicons5'
import UpscalerView from '@/components/creator/function/upscaler.vue'

import {creatorDict} from "@/dictionary/creatorDict";
import {sdControllerApi} from "@/api/sd/sdController.api";
import OpenPoseView from "@/views/pages/configuration/openpose/index.vue";
import Bus from "@/components/file/box/GlobalUploader/utils/bus";


const imageModelShow = ref(false)
const detailDesignShow = ref(false)
const selectRow = ref(null)
const selectIndex = ref(0)
const currentTaskNum = ref(0)
const progressModal = ref(false)
const boardList = ref([])
const mp3Url = ref('')
const audio = ref(null)
const drawerWidth = ref(0)

const {storyBoardSelectType, upscaleEngineTypeOptions, realESRGANModelTypeOptions, expandImageOption} = creatorDict()
const storyBoardSelectOption = ref("0")
const openPoseViewShow = ref(false)


const selectedBoard = ref(null)

const option = ref({
  voiceOption: [],
  characterOption: [],
  sceneOption: [],
  angleOption: [],
  cameraOption: []
})

const upscalers = ref(realESRGANModelTypeOptions.value)
const paintConfig = ref(null)
const stopLoop = ref(false)
const skipFlag = ref(true)
const runInBack = ref(false)
const upscaleForm = reactive({
  upscaleResize: 2,
  upscaleEngine: 'realesrgan',
  upscalerModel: 'realesr-animevideov3',
  getScalerModelLading: false
})


const batchOperationForm = reactive({
  batchOperationType: '0',
  batchOperationLoading: false,
  batchOperationModalShow: false,
  batchOperationStartNum: 0,
  batchOperationEndNum: 0,
  batchOperationAppointFlag: false,
  batchOperationFlag: false,
  loading: false
})


const upscaleModalShow = ref(false)

const resourceId = ref(null)

const {
  clientHeight,
  layoutHeaderHeight,
  darkTheme,
  tabsHeight
} = storeToRefs(useSystemStore());

// 任务状态
const taskStatus = ref({
  successNum: 0,
  failNum: 0
})


const props = defineProps({
  story: {
    type: Object,
    default: () => {
      return {}
    }
  },
  recoverGetTaskInfo: {
    type: Function,
    required: true
  }
})


// 列表字段
const createColumns = [
  {
    title: '序号',
    key: 'orderNum',
    width: 60
  },
  {
    title: '原文描述',
    key: 'content',
    width: 200,
    render(row) {
      return h(NInput, {
        value: row.content,
        type: 'textarea',
        style: 'height: 100px',
        disabled: true
      })
    }
  },
  {
    title: '关键词',
    key: 'prompt',
    width: 200,
    render(row, index) {
      return h(NInput, {
        value: row.prompt,
        type: 'textarea',
        style: 'height: 100px',
        onUpdateValue(v) {
          row.prompt = v;
          row.isChange = '1';
        },
        onBlur: function () {
          if (row.isChange == '1') {
            updateBoard(row)
          }
        }
      })
    }
  },
  {
    title: '详细设置',
    key: 'prompt',
    width: 200,
    render(row, index) {
      console.log(row.sceneList)
      return h(Detail, {
        characterList: row.characterList,
        sceneList: row.sceneList,
        angleList: row.angleList,
        cameraList: row.cameraList,
        index: index
      })
    }
  },
  {
    title: '骨骼图',
    key: 'openPose',
    width: 120,
    render(row) {
      const openPoseView = [h(NButton, {
        size: 'small',
        type: 'warning',
        onClick: () => {
          row.poseExampleBackground = null
          row.poseExampleImage = null
          row.openPose = null
          updateBoard(row)
        }
      }, {
        default: () => '撤销'
      }), h(NButton, {
        size: 'small',
        type: 'primary',
        style: 'margin-left:5px;margin-bottom:5px;',
        onClick: () => {
          selectedBoard.value = row;
          openPoseViewShow.value = true
        }
      }, {
        default: () => '选择'
      })]

      if (row.openPose != null && row.openPose.length > 0) {
        openPoseView.push(h(NImage, {
          lazy: true,
          height: '100',
          src: fileFunction.getOpenPoseImage(row?.poseExampleBackground)
        }))
      }
      return openPoseView
    }
  },
  {
    title: '音频',
    key: 'characterName',
    width: 60,
    render(row, index) {
      if (row.audioFileId) {
        return h(NIcon, {
          size: 20,
          onClick: () => {
            audio.value.src = fileFunction.getViewFilePathByUserFileId(row.audioFileId)
            audio.value.play()
          }
        }, {default: () => h(CaretForwardCircleSharpIcon)})
      } else {
        return '暂无'
      }
    }
  },
  {
    title: '关键帧方向',
    key: 'keyFrameDirection',
    width: 90,
    render(row, index) {
      console.log("keyFrameDirection:" + row.keyFrameDirection)
      if(row.keyFrameDirection === null || row.keyFrameDirection === undefined || row.keyFrameDirection === ''){
        row.keyFrameDirection = '4'
      }
      return h(NRadioGroup, {
        value: row.keyFrameDirection,
        onUpdateValue(v) {
          if (v != boardList.value[index].keyFrameDirection) {
            boardList.value[index].keyFrameDirection = v
            boardList.value[index].isChange = true
            updateBoard(boardList.value[index])
          }
        }
      }, {
        default: () => {
          return [
            h(NSpace, {
              style: 'margin-bottom: 10px;width:100%'
            }, {
              default: () => [
                h(NRadio, {
                  value: '1'
                }, {
                  default: () => '左到右'
                }), h(NRadio, {
                  value: '2'
                }, {
                  default: () => '上到下'
                }), h(NRadio, {
                  value: '3'
                }, {
                  default: () => '缩放'
                }), h(NRadio, {
                  value: '4'
                }, {
                  default: () => '随机'
                })]
            })]
        }
      })
    }
  },
  {
    title: '本镜配图',
    key: 'prompt',
    width: 150,
    align: 'center',
    render(row) {
      if (row.imgStatus === "SUBMITTED") {
        return "正在生成"
      }
      if (row.imgFileId == null || row.imgFileId.length === 0) {
        return '等待生成'
      }
      return h(NImage, {
        lazy: true,
        height: '100',
        src: fileFunction.getViewFilePathByUserFileId(row.imgFileId)
      })
    }
  },
  {
    title: '本镜配图集',
    key: 'prompt',
    width: 150,
    render(row, index) {
      if (row.imageList.length === 0) {
        return '等待生成';
      }
      return h(
          'div',
          {
            // style: 'min-height: 22px',
            onClick: () => {
              selectRow.value = row
              imageModelShow.value = true
            }
          },
          h(NImage, {
            lazy: true,
            height: '100',
            previewDisabled: true,
            src: fileFunction.getViewFilePathByUserFileId(row.imageList[0])
          })
      )
    }
  },
  {
    title: '操作',
    width: 100,
    align: 'center',
    render(row, index) {
      return [
        h(NButton, {
          size: 'small',
          block: true,
          loading: row.buttonLoading,
          type: 'primary',
          onClick: () => rePaint(row)
        }, {
          default: () => '生成图片'
        }),

        h(NButton, {
          size: 'small',
          block: true,
          style: 'margin-top: 10px',
          loading: row.upscaleLoading,
          type: 'info',
          onClick: () => upsacle(row)
        }, {
          default: () => '图片放大'
        }),

        h(NButton, {
          size: 'small',
          block: true,
          style: 'margin-top: 10px',
          type: 'primary',
          loading: row.audioButtonLoading,
          onClick: async () => await reTts(row)
        }, {
          default: () => '生成音频'
        })
        // , h(NButton, {
        //   size: 'small',
        //   block: true,
        //   style: 'margin-top: 10px',
        //   type: 'info',
        //   onClick: () => {
        //     console.log("index:{}", index)
        //     selectIndex.value = index
        //     selectRow.value = row
        //     detailDesignShow.value = true
        //   }
        // }, {
        //   default: () => '图片高级调整'
        // })
      ]
    }
  }
]



const getStoryBoardByChapterId = () => {
  tableLoading.value = true

  storyController.getStoryScheduleByChapterId(props.story.id, storyBoardSelectOption.value).then(res => {
    tableLoading.value = false
    if (res.code === 200) {
      boardList.value = res.data
      boardList.value.forEach((item: any) => {
        if (item.characterName) {
          item.characterList = item.characterName.split(",")
        }
        if (item.sceneName) {
          item.sceneList = item.sceneName.split(",")
        }
        if (item.camera) {
          item.cameraList = item.camera.split(",")
        }
        if (item.angle) {
          item.angleList = item.angle.split(",")
        }
      })
    } else {
      message.error(res.msg)
    }
  })
}


const updateBoard = (row: any) => {
  const param = {...row}
  delete param.characterList
  delete param.sceneList
  delete param.cameraList
  delete param.angleList
  storyBoardController.addOrUpdateBoard(param).then(res => {
    if (res.code !== 200) {
      message.error(res.msg)
    }
  })
}

/**
 * 重绘
 * @param row
 */
const rePaint = (row: any) => {
  // 设置当前状态为已提交
  row.buttonLoading = true
  storyBoardController.rePaintStoryBoardAndCheck(row.id, 3 * 60 * 1000).then(res => {
    if (res.taskStatus === 'SUCCESS') {
      const imageFiles = res.userFileId.split(',')
      row.imgFileId = imageFiles[0]
      for (let i = 0; i < imageFiles.length; i++) {
        row.imageList.push(imageFiles[i])
      }
    }
  }).catch(e => {
    window.$notification.error({
      title: "请求错误",
      content: "请查看绘画资源与百度翻译是否配置！！",
      duration: 5000,
      keepAliveOnHover: true
    })
  }).finally(() => {
    row.buttonLoading = false
  })
}

const reTts = async (row: any) => {
  row.audioStatus = "NOT_START"
  row.audioButtonLoading = true
  const res = await storyBoardController.reTtsStoryBoardAndCheck(row.id, 3 * 60 * 1000).then(res=>{
    console.log(res)
    if (res.taskStatus === 'SUCCESS') {
      row.audioFileId = res.userFileId
    }
  }).catch(e => {
    window.$notification.error({
      title: "请求错误",
      content: "系统异常,请稍后再试",
      duration: 5000,
      keepAliveOnHover: true
    })
  }).finally(() => {
    row.audioButtonLoading = false
  })
  console.log(res)
}


const startStoryTask = async () => {
  currentTaskNum.value = 0
  taskStatus.value = {
    successNum: 0,
    failNum: 0
  }
  progressModal.value = true
  for (const item of boardList.value) {
    currentTaskNum.value++
    try {
      const res_tts = await storyController.reTtsStoryBoard(item.id)
      const res = await storyBoardController.rePaintStoryBoardAndCheck(item.id, 3 * 60 * 1000)
      if (res.taskStatus === 'SUCCESS') {
        // 成功
        taskStatus.value.successNum++
      } else {
        // 失败
        taskStatus.value.failNum++
      }
    } catch (e) {
      taskStatus.value.failNum++
      message.error("系统异常,请稍后再试")
      break
    }
  }
  // 重载数据
  getStoryBoardByChapterId()
}

onMounted(async () => {
  // getTagAttribute()
  await getSetUpOption()
  getStoryBoardByChapterId()
  getStoryPaintConfig()
  drawerWidth.value = window.innerWidth
  window.addEventListener('resize', handleResize)
})

// 窗口宽度变化
const handleResize = () => {
  drawerWidth.value = window.innerWidth;
}


// 获取任务列表
const getSetUpOption = () => {
  storyController.getSetUpInfo(props.story.id).then(res => {
    if (res.code === 200) {
      option.value.angleOption = res.data.angleOption
      option.value.cameraOption = res.data.cameraOption
      option.value.sceneOption = res.data.sceneOption
      option.value.characterOption = res.data.characterOption
    }
  })
}

const Detail = defineComponent({
  props: {
    index: {
      type: Number,
      required: true
    },
    characterList: {
      type: Array,
      required: true
    },
    angleList: {
      type: Array,
      required: true
    },
    cameraList: {
      type: Array,
      required: true
    },
    sceneList: {
      type: Array,
      required: true
    }
  },
  setup(props) {
    return () => [
      h(NTreeSelect, {
        options: option.value.characterOption,
        placeholder: '请选择人物',
        size: 'small',
        style: 'width: 200px;margin-top:5px;',
        keyField: 'id',
        labelField: 'characterName',
        defaultExpandAll: true,
        multiple: true,
        value: props.characterList,
        onUpdateValue: (v: any) => {
          boardList.value[props.index].characterName = v.join(",")
          boardList.value[props.index].characterList = v
          updateBoard(boardList.value[props.index])
        }
      }),
      h(NTreeSelect, {
        options: option.value.angleOption,
        placeholder: '请选择视角',
        clearable: true,
        size: 'small',
        multiple: true,
        style: 'width: 200px;margin-top:5px;',
        keyField: 'en',
        labelField: 'zh',
        defaultExpandAll: true,
        value: props.angleList,
        onUpdateValue: (v: any) => {
          boardList.value[props.index].angle = v.join(",")
          boardList.value[props.index].angleList = v
          updateBoard(boardList.value[props.index])
        }
      }),
      h(NTreeSelect, {
        options: option.value.cameraOption,
        placeholder: '请选择镜头',
        size: 'small',
        clearable: true,
        keyField: 'en',
        labelField: 'zh',
        multiple: true,
        style: 'width: 200px;margin-top:5px;',
        defaultExpandAll: true,
        value: props.cameraList,
        onUpdateValue: (v) => {
          boardList.value[props.index].camera = v.join(",")
          boardList.value[props.index].cameraList = v
          updateBoard(boardList.value[props.index])
        }
      }),
      h(NTreeSelect,
          {
            options: option.value.sceneOption,
            placeholder: '请选择场景',
            size: 'small',
            clearable: true,
            multiple: true,
            keyField: 'id',
            labelField: 'sceneName',
            defaultExpandAll: true,
            style: 'width: 200px;margin-top:5px;',
            value: props.sceneList,
            onUpdateValue: (v) => {
              boardList.value[props.index].sceneName = v.join(",")
              boardList.value[props.index].sceneList = v
              updateBoard(boardList.value[props.index])
            }
          })
    ]
  }
})

const getStoryPaintConfig = () => {
  storyController.getStoryPaintConfig(props.story.id).then(res => {
    if (res.code === 200) {
      if (res.data != null) {
        resourceId.value = res.data.resourceId
        paintConfig.value = JSON.parse(res.data.paintConfigText)
        // console.log(paintConfig)
        // getUpscaler()
      }
    } else {
      message.error(res.msg);
    }
  })
}

// // 获取反推的算法
// const getUpscaler = () => {
//   sdControllerApi.getUpscaler(resourceId.value).then(res => {
//     if (res.code === 200) {
//       upscalers.value = JSON.parse(res.data)
//     } else {
//       message.error(res.message);
//     }
//   })
// }


const upsacle = (row: any) => {

  if (upscaleForm.upscalerModel === '') {
    message.warning("请选择放大算法")
    return
  }
  if (upscaleForm.upscalerModel === 'realesrgan-x4plus' && upscaleForm.upscaleResize !== 4) {
    message.warning("realesrgan-x4plus只能放大4倍")
    return
  }

  const param = {
    scale: upscaleForm.upscaleResize,
    upscaleEngine: upscaleForm.upscaleEngine,
    modelName: upscaleForm.upscalerModel,
    skipFlag: skipFlag.value,
    storyBoardId: row.id,
    storyId: props.story.id
  }
  row.upscaleLoading = true
  storyBoardController.upscale(param).then(res => {
    row.interrogateLoading = false
    if (res.code === 200) {
      row.imageList.push(res.data)
      row.imgFileId = res.data
      updateBoard(row)
    } else {
      message.error(res.msg)
    }
  }).finally(() => {
    row.upscaleLoading = false
  })
}


const startTask = async () => {
  if (runInBack.value) {
    const param = {
      operationType: batchOperationForm.batchOperationType,
      storyId: props.story.id,
      skipFlag: skipFlag.value,
      startNum: batchOperationForm.batchOperationStartNum,
      endNum: batchOperationForm.batchOperationEndNum
    }
    batchOperationForm.loading = true
    storyController.startStoryBatchTask(param).then(res => {
      if (res.code === 200) {
        props.recoverGetTaskInfo()
      }
    }).finally(() => {
      batchOperationForm.loading = false
      batchOperationForm.batchOperationModalShow = false
    })
  } else {
    stopLoop.value = false
    currentTaskNum.value = 0
    taskStatus.value = {
      successNum: 0,
      failNum: 0,
      totalNum: batchOperationForm.batchOperationEndNum - batchOperationForm.batchOperationStartNum + 1
    }
    batchOperationForm.batchOperationFlag = true
    for (let i = batchOperationForm.batchOperationStartNum;
         i <= batchOperationForm.batchOperationEndNum;
         i++) {
      if (stopLoop.value) {
        break
      }
      currentTaskNum.value++
      const item = boardList.value[i]
      if (batchOperationForm.batchOperationType === '0' || batchOperationForm.batchOperationType === '1') {
        if (skipFlag.value) {
          if (item.imgFileId != null && item.imgFileId.length > 0) {
            // 跳过
            taskStatus.value.successNum++
            continue
          }
        }
        // 开启绘画任务
        try {
          if (batchOperationForm.batchOperationType === '0') {
            // 同步发送
            await storyController.reTtsStoryBoard(item.id)
          }
          const res = await storyBoardController.rePaintStoryBoardAndCheck(item.id, 1.5 * 60 * 1000)
          if (res.taskStatus === 'SUCCESS') {
            // 成功
            taskStatus.value.successNum++
          } else {
            // 失败
            taskStatus.value.failNum++
          }
        } catch (e) {
          taskStatus.value.failNum++
        }
      } else {
        try {
          if (skipFlag.value) {
            if (item.audioFileId != null && item.audioFileId.length > 0) {
              // 跳过
              taskStatus.value.successNum++
              continue
            }
          }
          const res_tts = await storyBoardController.reTtsStoryBoardAndCheck(item.id, 30 * 1000)
          if (res_tts.status === 'SUCCESS') {
            // 成功
            taskStatus.value.successNum++
          } else {
            // 失败
            taskStatus.value.failNum++
          }
        } catch (e) {
          taskStatus.value.failNum++
        }
      }
    }
    // batchOperationForm.batchOperationModalShow = false
    batchOperationForm.batchOperationFlag = false
    // 重载数据
    getStoryBoardByChapterId()
  }
}

const batchUpscale = async () => {
  if (upscaleForm.upscalerModel === '') {
    message.warning("请选择放大算法")
    return
  }
  if (upscaleForm.upscalerModel === 'realesrgan-x4plus' && upscaleForm.upscaleResize !== 4) {
    message.warning("realesrgan-x4plus只能放大4倍")
    return
  }
  stopLoop.value = false
  currentTaskNum.value = 0
  taskStatus.value = {
    successNum: 0,
    failNum: 0
  }
  progressModal.value = true
  for (const item of boardList.value) {
    if (stopLoop.value) {
      break
    }
    currentTaskNum.value++
    try {
      const param = {
        scale: upscaleForm.upscaleResize,
        upscaleEngine: upscaleForm.upscaleEngine,
        modelName: upscaleForm.upscalerModel,
        skipFlag: skipFlag.value,
        storyBoardId: item.id,
        storyId: props.story.id
      }
      const res = await storyBoardController.upscale(param)
      if (res.code === 200) {
        // 成功
        taskStatus.value.successNum++
      } else {
        // 失败
        taskStatus.value.failNum++
      }
    } catch (e) {
      taskStatus.value.failNum++
    }
  }
  // 重载数据
  getStoryBoardByChapterId()
}


// 初始化自动任务表单
const initBatchOperationForm = () => {
  batchOperationForm.batchOperationStartNum = 0
  batchOperationForm.batchOperationEndNum = boardList.value.length - 1
  batchOperationForm.batchOperationType = '0'
  batchOperationForm.batchOperationAppointFlag = false
  batchOperationForm.batchOperationModalShow = true
  taskStatus.value.totalNum = 0
  taskStatus.value.successNum = 0
  taskStatus.value.failNum = 0
}

const chosenOpenPose = (openPose: any) => {
  selectedBoard.value.openPose = openPose.id
  selectedBoard.value.poseExampleBackground = openPose.poseExampleBackground
  selectedBoard.value.poseExampleImage = openPose.poseExampleImage
  updateBoard(selectedBoard.value)
  openPoseViewShow.value = false
}


const upscalerViewClose = () =>{
  upscaleModalShow.value = false
  getStoryBoardByChapterId()
}

Bus.on('refreshStoryConfig', () => {
  getSetUpOption()
  getStoryBoardByChapterId()
  getStoryPaintConfig()
})
</script>
